<template>
  <q-dialog
    :model-value="modelValue"
    @update:modelValue="$emit('update:modelValue', $event)"
    persistent
  >
    <q-card :style="$q.screen.gt.xs ? 'min-width: 800px' : 'width: 100%'">
      <q-card-section>
        <div class="text-h6">分配角色 - {{ userName }}</div>
      </q-card-section>

      <q-card-section>
        <div class="q-pa-md">
          <div class="text-subtitle2 q-mb-sm">当前角色</div>
          <q-chip
            v-for="role in assignedRoles"
            :key="role.roleId"
            removable
            @remove="removeRole(role.roleId)"
          >
            {{ role.roleName }}
          </q-chip>
          <div v-if="assignedRoles.length === 0" class="text-grey">暂无角色</div>
        </div>

        <q-separator class="q-my-md" />

        <div class="q-pa-md">
          <div class="text-subtitle2 q-mb-sm">可选角色</div>
          <q-select
            v-model="selectedRole"
            :options="availableRoles"
            label="选择角色"
            outlined
            emit-value
            map-options
            option-value="roleId"
            option-label="roleName"
          >
            <template v-slot:append>
              <q-btn
                icon="add"
                color="primary"
                dense
                flat
                @click="addRole"
                :disable="!selectedRole"
              />
            </template>
          </q-select>
        </div>

        <div class="flex justify-end q-gutter-sm q-mt-md">
          <q-btn label="取消" v-close-popup flat color="primary" />
          <q-btn label="保存" color="primary" @click="saveRoles" />
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { relatedRoleList, unrelatedRoleList, authRoleAdd, authRoleRemove } from '@/api/sys/user'

const props = defineProps({
  modelValue: Boolean,
  userId: Number,
  userName: String,
})

const emit = defineEmits(['update:modelValue', 'submit'])

const assignedRoles = ref([])
const availableRoles = ref([])
const selectedRole = ref(null)

// 加载角色数据
async function loadRoles() {
  try {
    const [assignedRes, availableRes] = await Promise.all([
      relatedRoleList(props.userId),
      unrelatedRoleList(props.userId),
    ])
    assignedRoles.value = assignedRes.data
    availableRoles.value = availableRes.data
  } catch (error) {
    console.error(' 加载角色数据失败:', error)
  }
}

// 添加角色
async function addRole() {
  try {
    await authRoleAdd({
      userId: props.userId,
      roleId: selectedRole.value,
    })
    await loadRoles()
    selectedRole.value = null
  } catch (error) {
    console.error(' 添加角色失败:', error)
  }
}

// 移除角色
async function removeRole(roleId) {
  try {
    await authRoleRemove({
      userId: props.userId,
      roleId: roleId,
    })
    await loadRoles()
  } catch (error) {
    console.error(' 移除角色失败:', error)
  }
}

// 保存角色
async function saveRoles() {
  emit('submit')
  emit('update:modelValue', false)
}

// 监听对话框显示状态
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      loadRoles()
    }
  },
)
</script>
